package org.lessim.socket;

import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @date: 2021/12/3 2:13 下午
 * @author: Menjoe
 */
public final class SessionPool {

    private SessionPool() {}

    private static final Map<Long, WebSocketSession> USER_SOCKET_SESSION_MAP = new ConcurrentHashMap<>();
    private static final Map<String, Long> SESSION_ID_2_UID = new ConcurrentHashMap<>();

    public static void put(Long uid, WebSocketSession session) {
        USER_SOCKET_SESSION_MAP.put(uid, session);
        SESSION_ID_2_UID.put(session.getId(), uid);
    }

    public static WebSocketSession get(Long uid) {
        return USER_SOCKET_SESSION_MAP.get(uid);
    }

    public static Set<Map.Entry<Long, WebSocketSession>> entrySet() {
        return USER_SOCKET_SESSION_MAP.entrySet();
    }

    public static void remove(String sessionId) {
        Long uid = SESSION_ID_2_UID.get(sessionId);
        SESSION_ID_2_UID.remove(sessionId);

        if (uid != null) {
            USER_SOCKET_SESSION_MAP.remove(uid);
        }
    }

}
